<template>
  <div :id="id" />
</template>

<script setup lang="ts" name="ECharts">
import { ref, onMounted, onBeforeUnmount, watch, computed, markRaw, nextTick } from 'vue';
import { EChartsType, ECElementEvent } from 'echarts/core';
import echarts, { ECOption } from './config';
import { useDebounceFn } from '@vueuse/core';
import { useGlobalStore } from '@/stores/modules/global';
import { storeToRefs } from 'pinia';
import { debounce } from 'lodash';

interface Props {
  option: ECOption;
  renderer?: 'canvas' | 'svg';
  resize?: boolean;
  theme?: Object | string;
  width?: number | string;
  height?: number | string;
  // onClick?: (event: ECElementEvent) => any;
}

const props = withDefaults(defineProps<Props>(), {
  renderer: 'canvas',
  resize: true
});

const $emit = defineEmits<{
  rightClick: [{ event?: ECElementEvent }];
  chartClick: [{ event?: ECElementEvent }];
}>();

const getRandomInt = (min: number, max: number) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

let id = ref('ref' + getRandomInt(1, 1000000));

const chartInstance = ref<EChartsType>();

const draw = debounce(() => {
  if (chartInstance.value) {
    chartInstance.value.setOption(props.option, true);
  }
}, 300);

watch(props, () => {
  draw();
});

const handleClick = (event: ECElementEvent) => {
  console.log(event, '点击');
  event.event?.stop();
  $emit('chartClick', { event });
  // props.onClick && props.onClick(event);
};

const handleRightClick = (event: ECElementEvent): any => {
  $emit('rightClick', { event });
};

const init = () => {
  const echartsId = document.getElementById(id.value);
  if (!echartsId) return;
  chartInstance.value = echarts.getInstanceByDom(echartsId);
  if (!chartInstance.value) {
    chartInstance.value = markRaw(
      echarts.init(echartsId, props.theme, {
        renderer: props.renderer
      })
    );
    chartInstance.value.on('click', handleClick);
    chartInstance.value.on('contextmenu', handleRightClick);
    draw();
  }
};

const resize = () => {
  if (chartInstance.value && props.resize) {
    chartInstance.value.resize({ animation: { duration: 300 } });
  }
};

const debouncedResize = useDebounceFn(resize, 300, { maxWait: 800 });

const globalStore = useGlobalStore();
const { maximize, isCollapse, tabs, footer } = storeToRefs(globalStore);

watch(
  () => [maximize, isCollapse, tabs, footer],
  () => {
    debouncedResize();
  },
  { deep: true }
);

onMounted(() => {
  nextTick(() => init());
  window.addEventListener('resize', debouncedResize);
});

onBeforeUnmount(() => {
  chartInstance.value?.dispose();
  window.removeEventListener('resize', debouncedResize);
});

defineExpose({
  getInstance: () => chartInstance.value,
  resize,
  draw
});
</script>
